<template>
    <div>
        <el-card style="width:100%;margin-bottom:30px;">
            <el-form :model="form" label-width="80px" style="padding-right:30px" :rules="rules" ref="formRef">
                <div style="margin-bottom:30px;margin-left:20px;font-size:20px;font-weight:bold;color:rgb(24, 226, 30)">利润统计</div>
                
                    <el-form-item label="统计月份" prop="period">
                    <div style="display:flex;align-items:center">
                        <div class="block">
                            <el-date-picker
                                v-model="month"
                                type="month"
                                value-format="yyyy-MM"
                                placeholder="选择月份">
                            </el-date-picker>
                        </div>
                        <el-button type="primary" @click="getdata" style="margin-left:30px;background-color:rgb(157, 188, 227);border:none">获取数据</el-button>
                    </div>
                    </el-form-item>
                    
                

                <div style="display:flex;align-items:center">
                    <el-form-item label="售书收入" prop="bookin">
                        <el-input v-model="form.bookin" id="bookin" disabled></el-input>
                    </el-form-item>
                    <el-form-item class="a" label="+会员收入" prop="vipin">
                        <el-input v-model="form.vipin" id="vipin" disabled></el-input>
                    </el-form-item>
                    <el-form-item class="a" label="-购书支出" prop="bookout" >
                        <el-input v-model="form.bookout" id="bookout" disabled></el-input>
                    </el-form-item>
                </div>
                <div style="display:flex;align-items:center">
                    <el-form-item label="-员工工资" prop="wage">
                        <el-input v-model="form.wage" id="wage"></el-input>
                    </el-form-item>
                    <el-form-item class="a" label="+其他收入" prop="otherin">
                        <el-input v-model="form.otherin" id="otherin" @blur="form.otherin=Number(form.otherin)"></el-input>
                    </el-form-item>
                    <el-form-item class="a" label="-其他支出" prop="otherout">
                        <el-input v-model="form.otherout" id="otherout"></el-input> 
                    </el-form-item>
                </div>

                <el-form-item label="=利润" prop="profit" width="40px">
                    <div style="display: flex; align-items: center;">
                        <el-input v-model="form.profit" id="profit" disabled></el-input>
                        <el-button type="primary" @click="reset" style="margin-left:30px;background-color:rgb(239, 233, 185);border:none">重置</el-button>
                        <el-button type="primary" @click="statistics" style="margin-left:30px;background-color:rgb(169, 200, 122);border:none">统计</el-button>
                        <el-button type="primary" @click="check" style="margin-left:80px;background-color:rgb(219, 42, 59);border:none;margin-right:10%">结账</el-button>
                    </div>
                </el-form-item>
            
            </el-form>
        </el-card>
        <div>
            <el-row :gutter="10" style="margin-bottom:20px">
                <el-col :span="24">
                    <el-card>
                        <div style="width:100%;height:400px">
                            <div>
                                <div style="display:flex">
                                    <el-input style="width:200px;margin-right:20px;" placeholder="按月份查询(YYYY-MM-01)" v-model="period"></el-input>
                                    <el-button type="primary" @click="load(1)">查询</el-button>
                                    <el-button type="info" @click="reset1" style="background-color:rgb(182, 233, 15);border:none">重置</el-button>
                                </div>
                                <div style="margin:10px 0;">
                                    <el-button  type="info" plain @click="exportData" style="background-color:rgba(238, 238, 94, 0.556);">批量导出</el-button>
                                </div>
                                <el-table :data="tableData" stripe :header-cell-style="{backgroundColor:'aliceblue',color:'#666'}" @selection-change="handleSelectionChange">
                                    <el-table-column type="selection" width="70" align="center"></el-table-column>
                                    <el-table-column prop="period" label="月份"></el-table-column>
                                    <el-table-column prop="bookin"  label="售书收入"></el-table-column>
                                    <el-table-column prop="vipin"  label="会员收入"></el-table-column>
                                    <el-table-column prop="otherin"  label="其他收入"></el-table-column>
                                    <el-table-column prop="bookout" label="购书支出"></el-table-column>
                                    <el-table-column prop="wage" label="员工工资"></el-table-column>
                                    <el-table-column prop="otherout" label="其他支出"></el-table-column>
                                    <el-table-column prop="profit" label="利润"></el-table-column>
                                    <el-table-column label="操作" align="center" width="150">
                                        <template v-slot="scope">
                                            <el-button size="mini" type="danger" plain @click="del(scope.row.period)">取消结账</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                                <div style="margin:10px 0;">
                                    <el-pagination
                                    @current-change="handleCurrentChange"
                                    :current-page="pageNum"
                                    :page-sizes="[100, 200, 300, 400]"
                                    :page-size="pageSize"
                                    layout="total, prev, pager, next"
                                    :total="total">
                                    </el-pagination>
                                </div>
                        
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
            <div style="display:flex;align-items:center;margin:20px">
                <div style="font-weight:600;color:rgb(236, 229, 23)">选择月份：</div>
                <div class="block">
                    <el-date-picker
                        v-model="month"
                        type="month"
                        value-format="yyyy-MM"
                        placeholder="选择月份">
                    </el-date-picker>
                </div>
                <el-button type="primary" @click="getMonth" style="margin-left:30px;background-color:rgb(157, 188, 227);border:none">选择</el-button>
            </div>
            <el-row :gutter="10" style="margin-bottom:20px">
                <el-col :span="12">
                    <el-card>
                        <div style="width:100%;height:400px" id="pie1"></div>
                    </el-card>
                </el-col>
                <el-col :span="12">
                    <el-card>
                        <div style="width:100%;height:400px" id="pie2"></div>
                    </el-card>
                </el-col>
            </el-row>
            <div style="display:flex;align-items:center;margin:20px">
                <div style="font-weight:600;color:rgb(236, 229, 23)">选择年份：</div>
                <div class="block">
                    <el-date-picker
                        v-model="year"
                        type="year"
                        value-format="yyyy"
                        placeholder="选择年份">
                    </el-date-picker>
                </div>
                <el-button type="primary" @click="getYear" style="margin-left:30px;background-color:rgb(157, 188, 227);border:none">选择</el-button>
            </div>
            <el-row :gutter="10">
                <el-col :span="24">
                    <el-card>
                        <div style="width:100%;height:400px" id="line"></div>
                    </el-card>
                </el-col>
            </el-row>

        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
const option = {
    title:{
        text:'年利润走向图'
    },
    tooltip:{
        trigger:'axis'
    },
    xAxis: {
        type: 'category',
        data: []
    },
    yAxis: {
        type: 'value'
    },
    series: [
    {
        data: [],
        type: 'line',
        smooth:true
    }
    ]
};
const option1 = {
    title: {
        text: '该月收入分析图',
        subtext: '',
        left: 'center'
    },
    tooltip: {
        trigger: 'item'
    },
    legend: {
        orient: 'vertical',
        left: 'left'
    },
    series: [
    {
        name: '金额（￥）',
        type: 'pie',
        radius: '50%',
        data: [
        { value: 0, name: '售书收入' },
        { value: 0, name: '会员收入' },
        { value: 0, name: '其他收入' },
        ],
        emphasis: {
        itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
        }
    }
    ]
};
const option2 = {
    title: {
        text: '该月支出分析图',
        subtext: '',
        left: 'center'
    },
    tooltip: {
        trigger: 'item'
    },
    legend: {
        orient: 'vertical',
        left: 'left'
    },
    series: [
    {
        name: '金额（￥）',
        type: 'pie',
        radius: '50%',
        data: [
        { value: 0, name: '购书支出' },
        { value: 0, name: '员工工资' },
        { value: 0, name: '其他支出' },
        ],
        emphasis: {
        itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
        }
    }
    ]
};
export default{
    name:"Profit",
    data(){
        return {
            month:'',
            year:'',
            form:{bookin:0,bookout:0,vipin:0,wage:0,otherin:0,otherout:0,profit:0},
            tableData:[],
            pageNum:1,
            pageSize:5,
            total:0,
            period:'',
            periods:[],
            user:JSON.parse(localStorage.getItem('honey-user') || '{}'),
            rules:{
                period:[
                    {required:true,message:'请选择月份(YYYY-MM)',trigger:'blur'}
                ]
            },
        }
    },
    created(){
        this.load()
    },
    mounted(){
        let lineDom = document.getElementById('line');
        let lineChart = echarts.init(lineDom);

        let pie1Dom = document.getElementById('pie1');
        let pie1Chart = echarts.init(pie1Dom);
        pie1Chart.setOption(option1)

        let pie2Dom = document.getElementById('pie2');
        let pie2Chart = echarts.init(pie2Dom);
        pie2Chart.setOption(option2)


        this.$request.get('/profit/selectAll').then(res=>{
            option.xAxis.data=res.data.map(v=>v.period)||[]
            option.series[0].data=res.data?.map(v=>v.profit)||[]
            lineChart.setOption(option)
        })
    },
    methods:{
        getMonth(){
            this.$request.get('/profit/selectByPeriod1/'+this.month).then(res=>{
            if (res.code === '200') {   // 表示操作成功
            let pie1Dom = document.getElementById('pie1')
            let pie1Chart = echarts.init(pie1Dom)
            option1.series[0].data=[
            { value: res.data[0].bookin, name: '售书收入' },
            { value: res.data[0].vipin, name: '会员收入' },
            { value: res.data[0].otherin, name: '其他收入' }
            ]
            pie1Chart.setOption(option1)
            let pie2Dom = document.getElementById('pie2')
            let pie2Chart = echarts.init(pie2Dom)
            option2.series[0].data=[
            { value: res.data[0].bookout, name: '购书支出' },
            { value: res.data[0].wage, name: '员工工资' },
            { value: res.data[0].otherout, name: '其他支出' }
            ]
            pie2Chart.setOption(option2)
            } else {
                this.$message.error(res.msg)  // 弹出错误的信息
            }
            })
        },
        getYear(){
            this.$request.get('/profit/selectByPeriod1/'+this.year).then(res=>{
                if (res.code === '200') {   // 表示操作成功
                    let lineDom = document.getElementById('line')
                    let lineChart = echarts.init(lineDom)
                    option.xAxis.data=res.data.map(v=>v.period)||[]
                    option.series[0].data=res.data?.map(v=>v.profit)||[]
                    lineChart.setOption(option)
                } else {
                    this.$message.error(res.msg)  // 弹出错误的信息
                }
            })
        },
        getdata(){
            this.$request.get('/book/selectByShoptime/' + this.form.period).then(res => {
            if (res.code === '200') {   // 表示操作成功
                this.$message.success('查询成功')
                let totalBprice = 0;
                for (const item of res.data) {
                    totalBprice += item.bprice;
                }
                this.form.bookout=totalBprice
                this.load()
            } else {
                this.$message.error(res.msg)  // 弹出错误的信息
            }
            })
            this.$request.get('/sell/selectByTime/' + this.form.period).then(res => {
            if (res.code === '200') {   // 表示操作成功
                //this.$message.success('查询成功')
                let totalSprice = 0;
                for (const item of res.data) {
                    totalSprice += item.sprice;
                }
                this.form.bookin=totalSprice
                this.load()
            } else {
                this.$message.error(res.msg)  // 弹出错误的信息
            }
            })
            this.$request.get('/vip/selectByTime/' + this.form.period).then(res => {
            if (res.code === '200') {   // 表示操作成功
                //this.$message.success('查询成功')
                this.form.vipin=res.data.length*1000
                this.load()
            } else {
                this.$message.error(res.msg)  // 弹出错误的信息
            }
            })
        },
        statistics(){
            if(this.form.period){
                this.form.profit=this.form.bookin - this.form.bookout + this.form.vipin - this.form.wage - this.form.otherout +this.form.otherin
            }else{
                this.$message.error("请先选择日期")
            }
            this.load()
        },
        del(period) {
            
            this.$confirm('您确认取消记账吗？', '确认取消', {type: "warning"}).then(response => {
            this.$request.delete('/profit/delete/' + period).then(res => {
            if (res.code === '200') {   // 表示操作成功
                this.$message.success('操作成功')
                this.load(1)
            } else {
                this.$message.error(res.msg)  // 弹出错误的信息
            }
            })
            }).catch(() => {})
        },
        check(){
            if(this.form.period && this.form.profit){
            this.form.period=this.form.period+'-01'
            this.$confirm('您确认记账吗？', '确认', {type: "warning"}).then(response => {
                this.$request.get('/profit/selectByPeriod/'+this.form.period).then(res => {
                if (res.code === '200') {   // 表示操作成功
                    if(res.data==null){
                        this.$request.post('/profit/add',this.form).then(res => {
                        if (res.code === '200') {   // 表示操作成功
                            this.$message.success('记账成功')
                            this.reset()
                        } else {
                            this.$message.error(res.msg)  // 弹出错误的信息
                        }
                        })
                    }else{
                        this.$message.error("该月已记账！请勿重复记账")
                        this.reset()
                    }
                } else {
                    this.$message.error(res.msg)  // 弹出错误的信息
                }
                })
            }).catch(() => {})}else{
                this.$message.error("请先选择日期,获取数据并统计")
            }
        },
        reset(){
            this.form={bookin:0,bookout:0,vipin:0,wage:0,otherin:0,otherout:0,profit:0},
            this.load()
            this.$refs.formRef.resetFields()
        },
        reset1(){
            this.period=''
            this.load()
        },
        exportData(){
            if(!this.periods.length){
                window.open('http://localhost:9090/profit/export?token='+this.user.token+"&period="+this.period)
            }else{
                let periodStr=this.periods.join(',')
                window.open('http://localhost:9090/profit/export?token='+this.user.token+'&periods='+periodStr)
            }
        },
        handleSelectionChange(rows){
            this.periods=rows.map(v=>v.period)
        },
        load(pageNum) {  // 分页查询
        if(pageNum){
            this.pageNum=pageNum
        }
        this.$request.get('/profit/selectByPage', {
        params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            period: this.period,
        }
        }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        })
        },
        handleCurrentChange(pageNum) {
            this.load(pageNum)
        },
        
    }
}
</script>

<style scoped>
.a{
    margin-left: 20px;
}
</style>